package com.min.license.util;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class SystemUtil {

    private static String getCpuIdOnWindows() {
        String result = null;
        try {
            File file = File.createTempFile("tmp", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new FileWriter(file);
            String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                    + "Set colItems = objWMIService.ExecQuery _ \n"
                    + "   (\"Select * from Win32_Processor\") \n"
                    + "For Each objItem in colItems \n"
                    + "    Wscript.Echo objItem.ProcessorId \n"
                    + "    exit for  ' do the first cpu only! \n" + "Next \n";

            // + "    exit for  \r\n" + "Next";
            fw.write(vbs);
            fw.close();
            String path = file.getPath().replace("%20", " ");
            Process p = Runtime.getRuntime().exec(
                    "cscript //NoLogo " + path);
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
            file.delete();
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return result.trim();
    }

    private static String getCpuIdOnLinux() {
        StringBuilder result = new StringBuilder();
        try {
            String[] cmds = {"/bin/sh","-c","dmidecode -t processor | grep 'ID'"};
            Process process = Runtime.getRuntime().exec(cmds);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(
                        line.trim()
                            .replace("ID:","")
                            .replace(" ", "")
                );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static String getId() {
        String os = System.getProperty("os.name").toUpperCase();
        System.out.println("当前系统为：" +  os);
        if ("LINUX".equals(os)) {
            return getCpuIdOnLinux();
        } else {
            return getCpuIdOnWindows();
        }
    }

}
